package cn.dapeng.features;

import cn.dapeng.util.SleepingUtil;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * 信号量： 限流 最多允许有多少个线程同时运行
 *
 * 场景：乘客买票  车道、收费站
 */
public class Semaphore_T01 {

    public static void main(String[] args) {
        Semaphore semaphore = new Semaphore(1);
        new Thread(() -> {
            try {
                semaphore.acquire();

                System.out.println("t1 running");
                SleepingUtil.sleep(1, TimeUnit.SECONDS);
                System.out.println("t1 running");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                semaphore.release();
            }
        }).start();

        new Thread(() -> {
            try {
                semaphore.acquire();

                System.out.println("t2 running");
                SleepingUtil.sleep(1, TimeUnit.SECONDS);
                System.out.println("t2 running");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }finally {
                semaphore.release();
            }
        }).start();

    }
}
